package com.chezhujie.www.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.chezhujie.www.domain.Czjcommodity;
import com.chezhujie.www.domain.Czjcommodity3;
import com.chezhujie.www.service.Czjcommodity3Service;
import com.chezhujie.www.service.CzjcommodityService;
import com.sys.core.page.Pagination;
import com.sys.core.utils.ConvertObj;
import com.sys.core.utils.Fileupload;
import com.sys.core.utils.UUIDUtils;
import com.sys.user.base.controller.BaseController;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *   首页3个商品表
 * Created by 汤伟杰 on 2017/5/23.
 */
@Controller
@RequestMapping("/czjcommodity3")
public class Czjcommodity3Controller extends BaseController<Czjcommodity3> {
    @Autowired
    private Czjcommodity3Service czjcommodity3Service;
    @Autowired
    private CzjcommodityService czjcommodityService;

    /** 列表 **/
    @RequestMapping("/list.do")
    public String list(Integer pageNo, Integer pageSize, Czjcommodity3 czjcommodity3, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        setMsg(czjcommodity3,req,model);
        setCommodityId(model);
        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = 0;
        }
        try {
            Map<String, Object> params = ConvertObj.toMap(czjcommodity3);
            Pagination pagination = czjcommodity3Service.list(pageNo.intValue(), pageSize.intValue(), params, model);
            model.addAttribute("pagination", pagination);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed","获取首页3个商品表列表失败!"+e.getMessage());
        }
        model.addAttribute("entity", czjcommodity3);
        return "czjcommodity3/list";
    }
    /** 严选商品
     *  保存 **/
    @RequestMapping("/save.do")
    public String save(Czjcommodity3 czjcommodity3,
                       @RequestParam(value = "filePicPath", required = false) MultipartFile multipartFile_PicPath,
                      HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        try {

            if(StringUtils.isNotBlank(czjcommodity3.getId())){
                String picPath = czjcommodity3.getPicPath();
                setPicPath(czjcommodity3,multipartFile_PicPath,req);
                czjcommodity3Service.update(czjcommodity3);


            }else{
                czjcommodity3.setId(UUIDUtils.getUUID());
                setPicPath(czjcommodity3,multipartFile_PicPath,req);
                czjcommodity3Service.insert(czjcommodity3);
            }
            model.addAttribute("success", "保存首页严选商品成功");
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", "保存首页严选商品失败!详情："+e.getMessage());
        }
        return "redirect:list.do";
    }
    private void setPicPath(Czjcommodity3 czjcommodity3, MultipartFile multipartFile, HttpServletRequest req) throws Exception {
        if((!multipartFile.isEmpty())&&multipartFile.getSize()>0){
            String basePath = req.getSession().getServletContext().getRealPath("/");
            String path = basePath+"upload/czjcommodity3/"+czjcommodity3.getId()+"-"+ System.currentTimeMillis()+multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            Fileupload.createDir(basePath+"upload/czjcommodity3/");

            InputStream in = multipartFile.getInputStream();
            FileOutputStream out = new FileOutputStream(path);
            try {
                IOUtils.copy(in,out);
            } catch (IOException e) {
                e.printStackTrace();
                throw new Exception("上传图片失败！");
            }finally {
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
            }

            String picPath = "/"+path.replace(basePath, "");
            czjcommodity3.setPicPath(picPath);
        }
    }


    /** 详情 **/
    @RequestMapping("/detail.do")
    public String detail(@RequestParam(required = true)String id,Czjcommodity3 czjcommodity3, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        setMsg(czjcommodity3,req,model);
        setCommodityId(model);
        try {
            Czjcommodity3 entity = czjcommodity3Service.queryById(czjcommodity3.getId());
            model.addAttribute("entity", entity);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", "查询首页3个商品表出错!详情："+e.getMessage());
        }
        return "czjcommodity3/detail";
    }
    /** 新增或修改 **/
    @RequestMapping("/add.do")
    public String add(Czjcommodity3 czjcommodity3,

                      HttpServletRequest req, HttpServletResponse resp,
                      ModelMap model){
        setMsg(czjcommodity3,req,model);
//        setCommodityId(model);


        Map<String,Object> param = new HashMap<String,Object>();
        List<Map<String,Object>> listBusiness = czjcommodity3Service.getListBusinessId(param);

        model.addAttribute("listBusiness", listBusiness);
        Map<String, Object> data = new HashMap<String, Object>();
        if(StringUtils.isNotBlank(czjcommodity3.getId())){
            czjcommodity3 = czjcommodity3Service.queryById(czjcommodity3.getId());
            data = ConvertObj.toMap(czjcommodity3);
            if(StringUtils.isNotBlank(czjcommodity3.getCommodityId())){
                Czjcommodity commodity = czjcommodityService.queryById(czjcommodity3.getCommodityId());
                if(commodity!=null&&commodity.getBusinessId()!=null){
                    data.put("businessId", commodity.getBusinessId());
                    Map<String,Object> param2 = new HashMap<String,Object>();
                    param2.put("businessId", commodity.getBusinessId());
                    List<Map<String,Object>> listCommodity = czjcommodity3Service.getListCommodityId(param2);
                    model.addAttribute("listCommodityId", listCommodity);
                }



            }
            model.addAttribute("entity", data);
        }


        return "czjcommodity3/add";
    }
    /** 删除 **/
    @RequestMapping("/delete.do")
    public String delete(@RequestParam(required = true)String id,Czjcommodity3 czjcommodity3, HttpServletRequest req, HttpServletResponse resp,
                     ModelMap model){
        try {
            czjcommodity3Service.deleteById(czjcommodity3.getId());
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", e.getMessage());
        }
        return "redirect:list.do";
    }
    /** 获取商品信息通过商家id **/
    @RequestMapping("/getBusinessIds.do")
    public void getBusinessIds(@RequestParam(required = true)String id,HttpServletRequest req, HttpServletResponse resp,
                     ModelMap model){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("businessId",id);
        map.put("soldOut",0);
        List<Map<String, Object>> list = czjcommodityService.getListBy(map);
        writeJson(resp, JSONObject.toJSONString(list, SerializerFeature.WriteMapNullValue));

    }
    private void setCommodityId(ModelMap model) {
        Map<String,Object> param = new HashMap<String,Object>();
        List<Map<String,Object>> listCommodity = czjcommodity3Service.getListCommodityId(param);
        model.addAttribute("listCommodityId", listCommodity);

    }

    private void setMsg(Czjcommodity3 czjcommodity3,HttpServletRequest req, ModelMap model) {
        model.addAttribute("failed", req.getParameter("failed"));
        model.addAttribute("success", req.getParameter("success"));
        model.addAttribute("entity", czjcommodity3);
    }
}
